package BaseService

import (
	"gdshop-admin-go-api/app/request/BaseReq"
	"gdshop-admin-go-api/library/response"
	toolsDb "gdshop-admin-go-api/library/tools/db"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"strings"
)

// GetCondition 获取 查询条件
func GetCondition(r *ghttp.Request, condition g.Map, queryOp *BaseReq.QueryOp, asName string) {
	if queryOp == nil {
		return
	}
	tmp := ""
	// 处理 其他条件
	if queryOp.OtherWhere != nil {
		// 合并两个条件
		for k, v := range queryOp.OtherWhere(r) {
			condition[getFieldName(k, asName)] = v
		}
	}
	// 处理 KeyWordLikeFields LIKE 搜索方法
	if len(queryOp.KeyWordLikeFields) > 0 {
		keyWord := r.GetString("keyWord", "")
		// 先组合条件
		strTmps := g.ArrayStr{}
		// 组合值
		strVals := g.ArrayStr{}
		for _, v := range queryOp.KeyWordLikeFields {
			if keyWord != "" {
				// 有查询的时候才加入
				strTmps = append(strTmps, "("+getFieldName(v, asName)+" LIKE ?) ")
				// 如果有统一的查询则使用
				strVals = append(strVals, "%"+keyWord+"%")
			} else {
				// 没有统一的情况下
				tmp = r.GetString(v, "")
				if tmp != "" {
					// 有查询的时候才加入
					strTmps = append(strTmps, "("+getFieldName(v, asName)+" LIKE ?) ")
					strVals = append(strVals, "%"+tmp+"%")
				}
			}
		}
		if len(strTmps) > 0 {
			condition["("+strings.Join(strTmps, " OR ")+")"] = strVals
		}
	}
	// 处理 FieldsEq 等于方法
	if len(queryOp.FieldsEq) > 0 {
		for _, v := range queryOp.FieldsEq {
			tmp = r.GetString(v, "")
			if tmp != "" {
				condition[getFieldName(v, asName)] = tmp
			}
		}
	}
}
func getFieldName(fieldName, asName string) string {
	// 判断列名是否带 .
	tmps := strings.Split(fieldName, ".")
	if len(tmps) > 1 {
		// 有带
		return fieldName
	} else {
		// 不带
		return asName + "." + fieldName
	}
}
func delBaseIgnoreProperty(data map[string]interface{}) {
	// 去除ID
	delete(data, "id")
	// 去除删除时间
	delete(data, "delete_at")
	delete(data, "create_at")
}
func DelIgnoreProperty(data map[string]interface{}, ignorePropertys []string) {
	delBaseIgnoreProperty(data)
	for _, v := range ignorePropertys {
		delete(data, v)
	}
}

func CategoryMove(r *ghttp.Request, tableName string, categoryId int, ids []string, fieldsName string) *response.JsonResponse {
	_, err := toolsDb.GetUnSafaTableAddDeleteWhere(r.GetCtx(), tableName).Where(
		"id IN (?)",
		ids).Update(g.Map{
		fieldsName: categoryId,
	})
	if err != nil {
		return response.FailByRequestMessage(r, err.Error())
	}

	return response.SuccessByRequest(r)
}
